﻿using Microsoft.Extensions.Options;
using ProxyServer.Endpoints;

namespace ProxyServer.Acme
{

    public class ServiceAcmeOptions
    {
        public string OrderId { get; set; } = default!;
        public bool RefreshOrder { get; set; }
        public ServiceDto Service { get; set; } = new ServiceDto(Guid.Empty, "", null, [], [], DateTimeOffset.Now, [], null);
        public string KeyAlgor { get; set; } = "ec";
        public int? KeySize { get; set; } = 256;
        public string? PfxPassword { get; set; }
        public int TimeoutSeconds { get; set; } = 300;
    }

    public abstract class ServiceAcmeState : AcmeState
    {
        protected readonly ILogger _logger;
        protected readonly IOptionsSnapshot<ServiceAcmeOptions> _options;

        protected virtual string OrderId => _options.Value.OrderId;
        protected virtual List<string> DomainNames => _options.Value.Service.Hosts;
        protected virtual bool RefreshOrder => _options.Value.RefreshOrder;
        protected virtual string KeyAlgor => _options.Value.KeyAlgor;
        protected virtual int? KeySize => _options.Value.KeySize;

        public ServiceAcmeState(ILogger logger, IOptionsSnapshot<ServiceAcmeOptions> options, AcmeStateMachineContext context) : base(context)
        {
            _logger = logger;
            _options = options;
        }
    }

    public abstract class SyncServiceAcmeState : ServiceAcmeState
    {
        protected SyncServiceAcmeState(ILogger logger, IOptionsSnapshot<ServiceAcmeOptions> service, AcmeStateMachineContext context) : base(logger, service, context)
        {
        }

        public override Task<IAcmeState> MoveNextAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var next = MoveNext();

            return Task.FromResult(next);
        }

        public abstract IAcmeState MoveNext();
    }
}
